package config

import (
	"io/ioutil"
	"gopkg.in/yaml.v2"
	"time"
	"os"
	"log"
)

type Config struct {
	Database Database
}

type Database struct {
	DBType  string
	Address string
	Name    string
	User    string
	Pass    string
	Port    int
}

const (
	CONFIGFILE = "config/config.yaml"
)

var (
	config *Config
	status bool
)

func init() {
	log.Println("[SYS]", time.Now().Local().Format("01-02 15:04:05"), "▶ System [Config loaded] ")
	config = new(Config)
	if _, err := os.Stat(CONFIGFILE); err == nil {
		status = loadFromFile()
	}
	if !status {
		loadFromDefault()
	}
}

func loadFromFile() bool {
	fileBytes, err := ioutil.ReadFile(CONFIGFILE)
	if err != nil {
		return false
	}
	if err = yaml.Unmarshal(fileBytes, config); err != nil {
		return false
	}
	return true
}

func loadFromDefault() {
	db := Database{
		Address: "localhost",
		Name:    "test",
		Port:    5432,
		User:    "housirvip",
		Pass:    "",
	}
	config = &Config{
		Database: db,
	}
	data, err := yaml.Marshal(config)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	err = ioutil.WriteFile(CONFIGFILE, data, os.ModePerm)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
}

func GetConfig() Config {
	return *config
}
